// 获取当前时间并格式化
import { ChatMessage, ChatMessageOrTimeLine } from "@/types/chat-message";

export function getISODateTime(date: Date): string {
  return date.toISOString();
}

// 将日期格式串转化为北京时间
export function convertUTCStringToBeijingTime(utcStr: string): string {
  // 先强制截取到毫秒前，避免尾部过长被部分环境误解析
  if (utcStr == null) {
    return "";
  }
  const cleanedStr = utcStr.trim().replace(/\.\d+/, "").replace(/Z?$/, "Z"); // 保证为 UTC

  // 创建 Date 对象（以 UTC 解析）
  const utcDate = new Date(cleanedStr);
  const beijingTimestamp = utcDate.getTime();
  const beijingDate = new Date(beijingTimestamp);

  // 格式化输出
  const pad = (n: number) => n.toString().padStart(2, "0");
  return `${beijingDate.getFullYear()}-${pad(beijingDate.getMonth() + 1)}-${pad(
    beijingDate.getDate()
  )} ${pad(beijingDate.getHours())}:${pad(beijingDate.getMinutes())}:${pad(
    beijingDate.getSeconds()
  )}`;
}

// 将日期格式串转化为北京时间
export function convertDateStringToBeijingTime(dateStr: string): string {
  // 创建 Date 对象（以 UTC 解析）
  const utcDate = new Date(dateStr);
  const beijingTimestamp = utcDate.getTime();
  const beijingDate = new Date(beijingTimestamp);

  // 格式化输出
  const pad = (n: number) => n.toString().padStart(2, "0");
  return `${beijingDate.getFullYear()}-${pad(beijingDate.getMonth() + 1)}-${pad(
    beijingDate.getDate()
  )} ${pad(beijingDate.getHours())}:${pad(beijingDate.getMinutes())}:${pad(
    beijingDate.getSeconds()
  )}`;
}

export function convertDateTimeToBeijingTime(time: number): string {
  if (time == null || isNaN(time)) {
    return "";
  }
  // 创建 Date 对象（以 UTC 解析）
  const beijingDate = new Date(time);
  // 格式化输出
  const pad = (n: number) => n.toString().padStart(2, "0");
  return `${beijingDate.getFullYear()}-${pad(beijingDate.getMonth() + 1)}-${pad(
    beijingDate.getDate()
  )} ${pad(beijingDate.getHours())}:${pad(beijingDate.getMinutes())}:${pad(
    beijingDate.getSeconds()
  )}`;
}

console.log(convertUTCStringToBeijingTime("2025-05-08T06:52:50.53517647")); //2025-5-8 06:52:50

export function convertToTodayTime(date: string): string {
  const inputDate = new Date(date);
  const today = new Date();

  const isSameDay =
    inputDate.getFullYear() === today.getFullYear() &&
    inputDate.getMonth() === today.getMonth() &&
    inputDate.getDate() === today.getDate();

  if (isSameDay) {
    return inputDate.toTimeString().split(" ")[0];
  } else {
    return date;
  }
}

export function groupMessagesWithTimeLine(
  messages: ChatMessage<any, any>[],
  thresholdMs = 1 * 60 * 1000 // 默认：5分钟间隔出现一次时间线
): ChatMessageOrTimeLine[] {
  const grouped: ChatMessageOrTimeLine[] = [];

  let lastTimestamp = 0;

  for (const message of messages) {
    const current = message.createTime;

    // 判断是否需要添加时间线
    if (
      grouped.length === 0 || // 第一个一定加
      current - lastTimestamp > thresholdMs || // 超过时间阈值
      new Date(current).getDate() !== new Date(lastTimestamp).getDate() // 跨天
    ) {
      grouped.push({
        type: "timeline",
        timestamp: current,
      });
      lastTimestamp = current;
    }

    // 插入消息本体
    grouped.push({
      type: "message",
      data: message,
    });
  }

  return grouped;
}
